<?php
namespace App\Admin\Controllers\Posts;

use App\Admin\Renderable\UsersRender;
use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Jobs\CalculateFollowsNumJob;
use App\Jobs\CalculateLikesNumJob;
use App\Jobs\Posts\UpdatePostOnlyTextJob;
use App\Models\Posts\WxPostsAddress;
use App\Models\Posts\WxTag;
use App\Models\Circle\WxCircle;
use App\Models\Shop\WxShopGoods;
use App\Models\User\WxUser;
use App\Models\WxTenant;
use App\Wen\Utils\CollecterUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\Settings;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\Auth\Permission;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\FormStep\Form as StepForm;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Alert;

class WxPostPublishController extends AdminController
{
    protected $title = '发文章';


    public function create(Content $content)
    {
        // 检查权限，有create-post权限的用户或者角色可以访问创建文章页面
        Permission::check('posts_publish');
        return parent::create($content);
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return $this->form();
    }

    /**
     * 保存
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function store()
    {
        return $this->form()->saving(function (Form $form) {
            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                return $this->fail(416001);
            }
            $posts_title = trim((strip_tags(_empty_default_($form->posts_title, ''))));
            $posts_content = $form->posts_content;
            $user_id = (int)($form->user_id);
            $circle_id = $form->circle_id;
            $tenant_id = $form->tenant_id;
            if(_empty_($tenant_id)){
                $tenant_id = 0;
            }
            $tags = $form->tags;
            $img_urls = $form->img_urls;
            $video = $form->video;
            $goods = $form->goods;
            $address_id = $form->address_id;

            $data = ['posts_content'=>$posts_content, 'user_id'=>$user_id,
                'circle_id'=>$circle_id, 'tags'=>$tags, 'img_urls'=>$img_urls,
                'video'=>$video, 'goods'=>$goods, 'address_id'=>$address_id];
            $form->data__ = json_encode($data);

            $posts_content_raw = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '',$posts_content);
            if( ( strlen($posts_content_raw) != strlen($posts_content) ) || mb_strlen($posts_content_raw) > 2000 ){
                if(!_empty_($video)){
                    $posts_content .= '<video src="' . $video . '"></video>';
                }else if(!_empty_($img_urls)){
                    $img_arr = explode(',', $img_urls);
                    if($img_arr){
                        foreach ($img_arr as $url){
                            $posts_content .= '<img src="'.$url.'">';
                        }
                    }
                }
            }
            $posts_content = PostUtils::post_icon_inline_process($posts_content);
//            $posts_content = CollecterUtils::content_media_process( $posts_content, 1);

            $res = PostsRepositores::admin_add('', $user_id, $posts_title, $posts_content, $circle_id, $tags, $goods, $img_urls, $video, $address_id, '', '', $tenant_id);
            if ($res) {
                CalculateLikesNumJob::dispatch($res);
                CalculateFollowsNumJob::dispatch($user_id);
                UpdatePostOnlyTextJob::dispatch(0);
                // 清空缓存
                $form->multipleSteps()->flushStash();
                // 拦截保存操作
                return response(
                    $form->multipleSteps()
                        ->done()
                        ->render()
                );
            } else {
                // 抛出错误
                return $this->fail(416001, $res);
            }

        })->store();
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {

    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(null, function (Form $form) {
            $form->action('/posts/publish/step');
            $form->disableListButton();

            $form->multipleSteps()
                ->remember() // 记住表单步骤，默认不开启
                ->width('950px')
                ->add('基本信息', function (StepForm $step) {

                    if(__system_is_model_enable('ycookies', 'caijiwebinfo')) {
                        $step->caijiwebinfo('采集web信息')->titleClass('art_title') // 插入文章标题到对应的class
                        ->contentClass('art_content'); // 插入文章内容到对应的class;
                    }

                    $step->html(function (){
                        return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">攻略：如何控制最后发布的是笔记还是图文，关键点在于编辑器里面是否上传了图片，如果编辑器里面有图片，系统就会认定它为图文</div>';
                    }, '');
                    if(__system_is_model_enable('laradocs', 'dcat-neditor')){
                        $info = '<i class="fa fa-exclamation-circle"></i> 此功能用于管理员新增内容。';
                        $step->html(Alert::make($info)->info());
                        $step->text('posts_title', '图文标题（选填）')->help('普通笔记不会显示标题')->setElementClass('art_title');
                        $step->neditor('posts_content', '文章内容')->setElementClass('art_content');
                    }else{
                        $info = '<i class="fa fa-exclamation-circle"></i> 此功能用于管理员新增内容，目前使用的是默认编辑器<br/>1、如需上传图片需要在.env文件里配置cos<br/>
2、如含有表格，请在前端发布，否则表格显示会不友好<br/>3、若不喜欢用该编辑器，群主也适配了另外一个Neditor编辑器(可135编辑器配合)，请在<a href="'.admin_url('extension').'" target="_blank">[扩展模块]</a>菜单里启用';
                        $step->html(function () use ($info) {
                            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.$info.'</div>';
                        }, '');
                        $step->text('posts_title', '图文标题（选填）')->help('普通笔记不会显示标题')->setElementClass('art_title');
                        $step->editor('posts_content', '文章内容')->required()->setElementClass('art_content');
                    }


//                    $step->multipleSelectTable('user_id', '用户')
//                        ->title('用户')
//                        ->max(2)
//                        ->from(UsersRender::make())
//                        ->model(WxUser::class, 'id', 'user_name')->saving(function ($v) {
//                            if(is_array($v) && count($v) > 0){
//                                return $v[0];
//                            }else if(is_numeric($v)){
//                                return $v;
//                            }
//                            return 0;
//                        })->required();

                    $step->select('user_id', '用户')->options(function ($id) {
                        if($id){
                            $user = \App\Models\User\WxUser::find($id);
                            if ($user) {
                                return [$user->id => $user->user_name];
                            }
                        }
                    })->ajax('select/users')->required();

                    $step->select('circle_id',env('circle_call', '圈子'))
                        ->options(WxCircle::pluck('circle_name','id'));

                    $step->select('tenant_id','分站')
                        ->options(WxTenant::pluck('name','tenant_id'))->default(0)->required();
                })
                ->add('关联信息', function (StepForm $step) {
//                    $step->multipleSelect('tags','话题')
//                        ->options(WxTag::limit(10)->pluck('tags_name','id'));

                    $step->multipleSelect('tags', '话题')->options(function ($id) {
                        if(!is_array($id) && $id) {
                            $tag = WxTag::find($id);
                            if (!_empty_($tag)) {
                                return [$tag->id => $tag->tags_name];
                            }
                        }else{
                            return null;
                        }
                    })->ajax('select/tags');

                    $step->multipleImage('img_urls', '图片')->uniqueName()->url('files/uploads')
                        ->autoUpload()->sortable()->help('如果存在视频的情况下，则第一张图片为该视频的封面使用，其余图片丢弃');
                    $step->file('video', '视频')->uniqueName()->url('files/uploads')->maxSize(999999999)
                        ->autoUpload();

                    $step->multipleSelect('goods', '商品')->options(function ($id) {
                        if(!is_array($id) && $id) {
                            $good = WxShopGoods::find($id);
                            if (!_empty_($good)) {
                                return [$good->id => $good->name];
                            }
                        }else{
                            return null;
                        }
                    })->ajax('select/shop/goods');


                    $step->select('address_id', '地址')->options(function ($id) {
                        if($id){
                            $address = WxPostsAddress::find($id);
                            if ($address) {
                                return [$address->id => $address->address_name];
                            }
                        }
                    })->ajax('select/posts/address');

                })
                ->done(function () use ($form) {

                    $data = [
                        'title'       => '发表成功',
                        'description' => '点击返回可到达文章列表，也可以继续发表新文章',
                        'createUrl'   => ''.admin_url('posts/publish'),
                        'backUrl'     => ''.admin_url('posts/index'),
                    ];

                    return view('dcat-admin.form-step::completion-page', $data);
                });
        });
    }
}
